import { openDB } from "idb";

const DB_NAME = "uploadDB";
const STORE_NAME = "files";

const useIndexedDB = () => {
  const initDB = async () => {
    return openDB(DB_NAME, 1, {
      upgrade(db) {
        if (!db.objectStoreNames.contains(STORE_NAME)) {
          db.createObjectStore(STORE_NAME, { keyPath: "filename" });
        }
      },
    });
  };

  // 添加/更新文件
  const addFile = async (fileData) => {
    const db = await initDB();
    await db.put(STORE_NAME, fileData);
  };

  // 获取所有文件
  const getAllFiles = async () => {
    const db = await initDB();
    return db.getAll(STORE_NAME);
  };

  // 删除单个文件
  const deleteFile = async (filename) => {
    const db = await initDB();
    await db.delete(STORE_NAME, filename);
  };

  // 清空所有文件
  const clearAllFiles = async () => {
    const db = await initDB();
    await db.clear(STORE_NAME);
  };

  return { addFile, getAllFiles, deleteFile, clearAllFiles };
};

export default useIndexedDB;
